/**
 * Author: Li
 * Date: 10/30/2025 21:07
 * Description: http请求
 */
import axios from "axios"
import { ACCESS_TOKEN } from "@/constants/key"
import debounce from "lodash/debounce"
import { responseType } from "@/constants/response-type"

/**
 * 防抖
 * 2秒内只弹一次错误提示
 */
const showErrorMessage = debounce(
  function (message) {
    $message.error(message)
  },
  2 * 1000,
  { leading: true, trailing: false },
)

const http = axios.create({
  baseURL: import.meta.env.VITE_BASE_PATH,
  timeout: 20 * 1000, // http超时
})

// 拦截http请求发送，配置token
http.interceptors.request.use((config) => {
  // const token = localStorage.getItem("token")
  const token = $storage.get(ACCESS_TOKEN)
  if (token) {
    config.headers.Authorization = token
  }
  return config
})

// 拦截http请求返回，处理错误
http.interceptors.response.use(
  (response) => {
    const res = response.data
    const code = res.code
    // 处理响应是blob文件的情况
    if (res instanceof Blob) {
      // 如果是Blob文件，期望后端返回excel的表格文件，实际后端返回了JSON异常数据
      // 判断Blob是正常的excel文件，还是异常的JSON数据，如果是异常的JSON数据，我们要弹窗提示异常信息
      if (res.type === "application/json") {
        const reader = new FileReader()
        reader.addEventListener("loadend", () => {
          const result = JSON.parse(reader.result) || {}
          showErrorMessage(result.message)
        })
        reader.readAsText(res, "utf-8")
      }
    } else if (code === "200") {
      // 正常的请求结果
      return Promise.resolve(res.data)
    } else {
      showErrorMessage(res.message)
      return Promise.reject(res.message)
    }
  },
  // 处理http异常
  (error) => {
    const response = error.response
    let msg = null
    if (response) {
      // 处理文件异常
      if (response.data instanceof Blob) {
        const reader = new FileReader()
        reader.addEventListener("loadend", () => {
          const result = JSON.parse(reader.result) || {}
          showErrorMessage(result.message)
        })
        reader.readAsText(response.data, "utf-8")
        return Promise.reject(error)
      }
      if (response.data && response.data.message) {
        msg = response.data.message
      } else {
        msg = responseType[response.status] || "未知的异常"
      }
    } else if (error instanceof axios.Cancel) {
      msg = "已取消"
    } else {
      msg = responseType[error.code || error.message] || "未知的异常"
    }
    showErrorMessage(msg)
    return Promise.reject(error)
  },
)

export default http
